package utils

import (
	"sync"

	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
)

type listenerItem struct {
	queueName string
	handler   func(msg string)
}

type taskItem struct {
	taskName string
	task     func()
}

var (
	ServerRunWg  = &sync.WaitGroup{}
	TaskList     = make([]taskItem, 0)
	ListenerList = make([]listenerItem, 0)
)

func RegisterTask(taskName string, task func()) {
	TaskList = append(TaskList, taskItem{
		taskName: taskName,
		task:     task,
	})
}

func RegisterListener(queueName string, handler func(msg string)) {
	ListenerList = append(ListenerList, listenerItem{
		queueName: queueName,
		handler:   handler,
	})
}

func RunTasksWithWg() {

	if len(TaskList) == 0 {
		return
	}

	for _, item := range TaskList {
		ServerRunWg.Add(1)
		go func() {
			defer func() {
				if panicErr := recover(); panicErr != nil {
					logs.Error("RunTaskWithWg task %s error, %s", item.taskName, PanicTrace(panicErr))
				}
				logs.Info("RunTaskWithWg task %s done", item.taskName)
				ServerRunWg.Done()
			}()
			item.task()
		}()
	}

}

func RunListenersWithWg() {

	if len(ListenerList) == 0 {
		return
	}

	mqListen := GetRabbitMq()
	for _, item := range ListenerList {
		ServerRunWg.Add(1)
		go func() {
			var err error
			defer func() {
				if panicErr := recover(); panicErr != nil {
					logs.Error("RunListenersWithWg listener %s error, %s", item.queueName, PanicTrace(panicErr))
					ServerRunWg.Done()
				}
			}()
			err = mqListen.Listen(item.queueName, item.handler)
			if err != nil {
				logs.Error("RunListenersWithWg listener %s failed to start: %s", item.queueName, err)
				ServerRunWg.Done()
			}
		}()
	}
}

func RunHttpServerWithWg(httpPort string) {
	ServerRunWg.Add(1)
	go func() {
		defer func() {
			if panicErr := recover(); panicErr != nil {
				logs.Error("RunHttpServerWithWg error, %s", PanicTrace(panicErr))
			}
			logs.Error("RunHttpServerWithWg done")
			ServerRunWg.Done()
		}()
		beego.Run(httpPort)
	}()
}
